package org.example.interceptor;

import org.example.component.BeanContext;
import org.example.entity.ExcludePathPatterns;
import org.example.util.JwtUtil;
import org.example.util.ValidationUtil;
import org.json.JSONObject;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName JwtInterceptor
 * @Description: TODO
 * @Author ChenYuan
 * @Date 2020/12/9
 * @Version V1.0
 **/
public class JwtInterceptor implements HandlerInterceptor {

    public static final Integer JWT_ERROR = 500;

    // 查询数据库中不需要校验的路径  我这里就不实现了
    // private ExcludePathPatternsMapper excludePathPatternsMapper= BeanContext.getBean(ExcludePathPatternsMapper.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestUri = request.getRequestURI();
        // 多个系统使用 确定是哪个系统的路径
        //ExcludePathPatterns excludePathPatterns=new ExcludePathPatterns();
        // excludePathPatterns.setSource(GlobalConstant.H5);
        // 查询数据库中不需要校验的路径
        // List<ExcludePathPatterns> excludePathPatternsList=excludePathPatternsMapper.selectByExcludePathPatterns(excludePathPatterns);

        // 手动设置数据库查回来的数据
        List<ExcludePathPatterns> excludePathPatternsList = new ArrayList<>();
        ExcludePathPatterns excludePathPatternsTemp = new ExcludePathPatterns();
        excludePathPatternsTemp.setUrl("/test/**");
        excludePathPatternsList.add(excludePathPatternsTemp);

        for(ExcludePathPatterns pathPatterns:excludePathPatternsList){
            String url=pathPatterns.getUrl();
            if(url.contains("/**")){
                int length= url.indexOf("/**");
                url=url.substring(0,length);
            }
            if (requestUri.contains(url)) {
                // 排除即是提前返回true 不进行token 校验
                return true;
            }
        }

        if("OPTIONS".equals(request.getMethod().toUpperCase())){
            // 通过所有OPTION请求
            return true;
        }else{
            //获取请求头中的token
            String token = request.getHeader("token");
            if(ValidationUtil.isNotEmpty(token)){
                try {
                    Map<String,String> verify = JwtUtil.verifyTokenHs256(token);
                    if (ValidationUtil.isNotEmpty(verify) && ValidationUtil.isNotEmpty(verify.get("mobile"))){
                        // 通过验证
                        return true;
                    } else {
                        //未通过验证
                        outError(response);
                        return false;
                    }
                }catch(Exception e){

                }
            }
            outError(response);
            return false;
        }
    }

    /**
     * 输出JSON格式错误信息
     * @param response
     * @throws IOException
     */
    private void outError(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        JSONObject res = new JSONObject();
        res.put("status",JWT_ERROR);
        res.put("msg","token过期！");
        PrintWriter out = null ;
        out = response.getWriter();
        out.write(res.toString());
        out.flush();
        out.close();
    }
}
